package nc.tb.ctl;

import java.util.HashMap;

import nc.tb.app.CommonPlan;
import nc.tb.app.vo.MdAttachmentVO;
import nc.tb.pub.NtbEnv;
import nc.tb.pub.cache.NtbCacheManager;
import nc.tb.pub.data.INtbCache;
import nc.tb.pub.services.NtbSuperServiceGetter;
import nc.tb.pub.util.NtbLogger;
import nc.vo.pub.BusinessException;

public class AttachFileCTL implements INtbCache {
	
	private final static String CACHE_KEY = "AttachFileCTL";
	
	private HashMap<String,Boolean> hm_planHasFile;

	private AttachFileCTL() {
		hm_planHasFile = new HashMap<String,Boolean>();
	}

	public void clearCache() {
		if (hm_planHasFile != null)
			hm_planHasFile.clear();
		aAttachFileCTL = null;
	}
	
	private static AttachFileCTL aAttachFileCTL = null;
	public static AttachFileCTL getInstance() {
		if (NtbEnv.isUICall) {
			if(aAttachFileCTL == null) {
				aAttachFileCTL = new AttachFileCTL();
				NtbCacheManager.putCacheInstance(CACHE_KEY, aAttachFileCTL);
			}
			return aAttachFileCTL;
		}
		AttachFileCTL inst =(AttachFileCTL )NtbCacheManager.getCacheInstance(CACHE_KEY);
		if(inst == null) {
			inst = new AttachFileCTL();
			NtbCacheManager.putCacheInstance(CACHE_KEY, inst);
		}
		return inst;
	}
	
	public void addValues(CommonPlan[] plans) {
		if (plans == null)
			return;
		StringBuffer sb = new StringBuffer();
		for (int i=0; i<plans.length; i++) {
			String pk = plans[i].getPrimaryKey();
			if (!hm_planHasFile.containsKey(pk)) {
				if (sb.length() > 0)
					sb.append(",");
				sb.append("'").append(pk).append("'");
				hm_planHasFile.put(pk, new Boolean(false));
			}
		}
		if (sb.length() == 0)
			return;
		try {
			MdAttachmentVO[] vos = null;
			if (plans.length > 1000) {
				vos = (MdAttachmentVO[])NtbSuperServiceGetter.getINtbSuper().queryAll(MdAttachmentVO.class);
			}
			else {
				vos = (MdAttachmentVO[]) NtbSuperServiceGetter.getINtbSuper().queryByCondition(MdAttachmentVO.class,
						"pk_object in (" + sb.toString() + ")");
			}
			if (vos != null) {
				for (int i=0; i<vos.length; i++) {
					hm_planHasFile.put(vos[i].getPk_object(), new Boolean(true));
				}
			}
		} 
		catch (BusinessException e) {
			NtbLogger.printException(e);
		}
	}
	
	public void setValue(String pk_plan, boolean b) {
		hm_planHasFile.put(pk_plan, new Boolean(b));
	}
	
	public boolean hasAttachFile(String pk_plan) {
		Boolean b = hm_planHasFile.get(pk_plan);
		if (b == null) {
			try {
				MdAttachmentVO[] filevo = PlanCTL.queryAttachment(pk_plan);
				b = new Boolean(filevo!=null&&filevo.length!=0);
				hm_planHasFile.put(pk_plan, b);
			} 
			catch (Exception e) {
				NtbLogger.printException(e);
			}
		}
		return b == null ? false : b.booleanValue();
	}

}
